package info.emamian.droplet.worker.sms;

import java.io.File;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

/**
 * makes sure mongo is available during the application startup.
 * 
 * @author Peyman
 * 
 * 
 */
@Component
public class SMSInitilization implements ApplicationListener<ContextRefreshedEvent> {

	private static final Logger log = LoggerFactory.getLogger(SMSInitilization.class);

	// @Autowired
	// MongoTemplate mongoTemplate;

	@Autowired
	SMSService smsService;

	@Autowired
	ResourceLoader resourceLoader;

	@Autowired
	private ServletContext servletContext;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		log.info("===============================================================");
		log.info("SMSInitialization onApplicationEvent - ContextRefreshedEvent");
		// try {
		// // mongoTemplate.getDb();
		// log.info("Collection sms found : {}",
		// mongoTemplate.getCollectionNames().contains("sms"));
		// }
		// catch (Exception e) {
		// // TODO: handle exception
		// log.error("Mongo DB error during initialization", e);
		// }
		try {

			Resource res = resourceLoader.getResource("inputs/drugs.csv");
			File f = res.getFile();
			// f.getAbsoluteFile();
			DrugInfoHandler drugInfoHandler = new DrugInfoHandler(f);
			if (drugInfoHandler.getKewordsList() != null)
				for (String keyword : drugInfoHandler.getKewordsList()) {
					if (keyword != null && !keyword.trim().isEmpty()) {
						smsService.registerHandler(keyword.trim().toLowerCase(), drugInfoHandler);
						log.info(" drugInfoHandler added for keyword:{}", keyword);
					}
				}

			// log.info("Registered sms handler for drug : {}",
			// smsService.registerHandler("drug", new
			// DrugInfoHandler(event.getApplicationContext().getParent())));

		}
		catch (Exception e) {
			log.error("SMS service error during initialization", e);
		}
		log.info("===============================================================");

	}
}
